<template>



  <div style="margin: 0 20px; text-align: center">
    <div style="margin-top: 150px">
      <div style="font-size: 25px">登录</div>
      <div style="font-size: 15px; color: gray; margin-top: 15px">输入账号密码登录</div>
    </div>

    <div style="margin-top: 50px">
      <el-input v-model="form.username" type="text" placeholder="用户名/邮箱">
        <template #prefix>
          <el-icon><User /></el-icon>
        </template>
      </el-input>
      <el-input v-model="form.password" type="password" style="margin-top: 10px" placeholder="密码">
        <template #prefix>
          <el-icon><Lock /></el-icon>
        </template>
      </el-input>
    </div>



    <div style="margin-top: 40px">
      <el-button @click="login" style="width: 270px" type="success"> 立即登录</el-button>
    </div>

    <div>
      <el-divider>
        <span  style="color: gray; font-size: 13px"> 没有账号？</span>
      </el-divider>
    </div>

    <div style="margin-top: 40px">
      <el-button @click="register" style="width: 270px" type="primary"> 注册账号</el-button>
    </div>
  </div>
</template>

<script setup>
import {User,Lock} from "@element-plus/icons-vue";
import store from '@/store'
import {ElMessage} from "element-plus";
import {postWithToken} from "@/net/postAndGetMethodWithToken";
import router from "@/router";
import {reactive} from "vue";



const form = reactive({
    username: '',
    password: '',
})

const login = () =>{
  if(!form.username||!form.password){
    ElMessage.warning('请填写用户名和密码')
  }else{
    postWithToken('/api/user/login', JSON.stringify({
      userAccount: form.username,
      userPassword: form.password,
    }), (data, code, message) => {
      ElMessage.success("登录成功");

      localStorage.setItem('token', data.token)
      // 获取当前的 Content-Type 属性
      const currentContentType = store.state.authHeader['Content-Type']
      // 构造新的请求头对象
      const newHeader = {
        'Content-Type': currentContentType,
        'jwtToken': data.token,
      }
      // 将token添加到请求头中
      store.commit('setAuthHeader', newHeader )
      router.push({
            path: '/',
            headers: store.state.authHeader
          });

      console.log(store.state.authHeader)
        },(data, code, message) => {
      if(code === 40000){
        ElMessage.warning("该用户不存在")
      }else{
        ElMessage.warning("请检查账号或密码")
      }
    }
    )
  }
}
const register =() => {
  router.push({name: 'welcome-register'})
}


</script>

<style scoped>

</style>
